<template>
  <page-wrap back title="AI面评" hide-tab stay-still :hideSafeArea="true" :bg-color="uNavColor" @back-click="onBackClick">
    <image class="background-pic" :src="backgroundPic"></image>
    <div class="conter">
      <span class="interviewTitle">{{
        this.isFromIndex != 0 ? zhituInterviewInfo.title : baseInfo.title
      }}</span>
      <span v-if="this.isFromIndex == 0" class="interviewTime">{{ baseInfo.begin }} - {{ baseInfo.end }}</span>
      <span class="interviewTip">本次面试预计需要20分钟，请您提前调节音量，并全程开启摄像头和麦克风。请尽量在安静的环境中进行面试，祝您面试顺利！</span>
      <u-button class="interviewBegin" type="error" @click="beginAction">开始面试</u-button>

      <div class="bottom-tip-box">
        您可以点击
        <span class="bottom-red-text" @click="imitateInterviewAction">测试一下</span>
        熟悉面试流程
      </div>
    </div>
  </page-wrap>
</template>

<script>
import common from "@/api/common.js";
import {
  getInterviewDetail,
  beginInterview,
  reqZhituGetInfo,
  reqZhituGetBeginData,
  refAddPoint,
} from "@/api/modules/company.js";

export default {
  ccomponents: {},
  data() {
    return {
      // 接口分两类：企业 or C端
      isFromIndex: 0, // 0=企业HR，1=C端招聘会人才(zph)，2=C端职途学生(zhitu)，3=扎堆（zhadui）。

      zhituCareerId: "", // 职途职业id
      zhituInterviewInfo: {
        title: "",
      },
      zhituBeginData: {},
      zhituError: undefined,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      isLoading: false,
      backgroundPic: this.$imgBaseSelf + "aiInterview/headerBggril.png",
      baseInfo: {},
      interviewInfo: {},
      issure: {
        answerNum: 1,
        id: "",
        interviewNumber: "",
        questions: [],
      },
      recordId: "",
      infoId: "",
      channel: "",
    };
  },

  onLoad: function (options) {
    if (options) {
      console.log("🚀 ~ AI面评主页.接参 ~ options:", options);
      if (
        options.from &&
        (options.from == "zhitu" ||
          options.from == "zph" ||
          options.from == "zhadui")
      ) {
        if (!options.careerId) {
          uni.showModal({
            title: "出错",
            content: "数据有异常，请稍后再试",
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                uni.navigateBack();
              }
            },
          });
          return;
        }
        this.recordId = options.recordId;
        this.infoId = options.infoId;
        this.personId = options.personId;

        this.isFromIndex = options.from == "zph" ? 1 : 2;
        if (options.from == "zhadui") {
          this.isFromIndex = 3;
        }
        this.zhituCareerId = options.careerId;
        this.zhituGetInterviewInfo();
      } else if (options.data) {
        this.baseInfo = JSON.parse(options.data);
        console.log("🚀 ~ this.baseInfo:", this.baseInfo);
        this.getdata();
      }
      this.channel = options.channel || "";
      // this.personId = options.personId;
    }

    let idx = this.isFromIndex | 0;
    wx.reportEvent("ai_ready", {
      come_from: idx == 0 ? "企业邀请面试" : (idx = 2 ? "职途" : "其它"),
    });
  },
  mounted() {
    this.commitBuringPoint("enterInterviewReady");
  },
  // // 对于uni-app，可以通过onBackPress选项来监听返回事件
  // onBackPress(options) {
  //   console.log("🚀 ~ file: interviewReady.vue:68 ~ onBackPress ~ options:", options)
  //   // options.from 用来判断来源，特定场景才弹窗
  //   if (options.from === 'backbutton') {
  //     // 显示确认对话框
  //     uni.showModal({
  //       title: '提示',
  //       content: '确定要离开当前页面吗？',
  //       success: (res) => {
  //         if (res.confirm)
  //           // 用户点击了确定，可以正常返回上一页
  //           uni.navigateBack();
  //         } else if (res.cancel) {
  //           // 用户点击了取消，不做任何事情
  //         }
  //       }
  //     });

  //     // 阻止默认的返回行为
  //     return true;
  //   }

  //   // 非按钮返回（比如右滑返回），不弹提示
  //   return false;
  // },

  methods: {
    onBackClick() {
      // 弹出模态框
      uni.showModal({
        title: "提示",
        content: "确定要离开当前页面吗？",
        success: (res) => {
          if (res.confirm) {
            // 用户点击确定
            uni.navigateBack();
          } else if (res.cancel) {
            // 用户点击取消
          }
        },
      });
      // 阻止事件继续传播
      return false;
    },

    ///////// 职途C端 begin /////////

    // 获取面试信息
    zhituGetInterviewInfo() {
      this.isLoading = true;
      let type = "";
      if (this.isFromIndex == 3) {
        type = "demonstrate";
      } else if (this.isFromIndex == 1) {
        type = "zph";
      } else {
        type = "zt";
      }
      if (this.infoId == "undefined") {
        this.infoId = "";
      }
      let params = {
        positionId: this.zhituCareerId,
        // modelType: this.isFromIndex == 1 ? "zph" : "zt"
        modelType: type,
        id: this.infoId,
      };

      reqZhituGetInfo(params)
        .then((res) => {
          console.log("🚀 ~ 职途C端.面试信息~ res:", res);
          this.isLoading = false;
          if (res.code == 200) {
            this.zhituInterviewInfo = res.data;
            this.zhituError = undefined;
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "error",
            });
            this.zhituError = res;
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },

    // 获取开始面试数据
    zhituGetStartInfo() {
      this.isLoading = true;
      let params = {
        infoId: this.zhituInterviewInfo.id,
        personId: this.personId,
        recordId: this.recordId,
      };

      reqZhituGetBeginData(params)
        .then((res) => {
          console.log("🚀 ~ 职途C端.推流数据~ res:", res);
          this.isLoading = false;
          if (res.code == 200) {
            this.zhituBeginData = res.data;
            this.gotoNext();
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "error",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
          uni.showToast({
            title: "请求异常，请稍候再试",
            icon: "error",
          });
        });
    },

    ///////// 职途C端 end /////////

    // 获取直播连接数据
    getdata() {
      this.isLoading = true;
      let params = {
        interviewNumber: this.baseInfo.num,
        personPhone: this.baseInfo.phone,
        userName: this.baseInfo.name,
      };
      beginInterview(params)
        .then((res) => {
          console.log("🚀 ~ 企业端 - 获取直播信息 ~ res:", res);
          this.isLoading = false;
          if (res.code == 200) {
            this.interviewInfo = res.data;
            if (this.interviewInfo.status == "started") {
              this.reqInterviewDetail();
            } else {
              uni.showToast({
                title: this.interviewInfo.popUp + "",
                icon: "none",
              });
            }
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },
    // 获取问题列表
    reqInterviewDetail() {
      let params = {
        id: "",
        interviewNumber: this.baseInfo.num,
        hasAnswer: false,
        interviewToken: this.interviewInfo.interviewToken,
        personPhone: this.baseInfo.phone,
      };
      getInterviewDetail(params).then((res) => {
        console.log("🚀 ~ 企业端 - 获取题目信息  ~ res:", res);
        if (res.code == 200) {
          this.issure = res.data;
        }
      });
    },

    // 模拟面试
    imitateInterviewAction() {
      let data = {
        isFromIndex: this.isFromIndex,
        isTest: true,
      };
      uni.setStorage({
        key: "params-interviewReady",
        data: data,
        success: function () {
          uni.navigateTo({
            url: "./interviewBegin",
          });
        },
      });
    },

    beginAction() {
      if (!this.issure.questions || !this.interviewInfo) {
        uni.showToast({
          title: "数据异常，请刷新后再试",
          icon: "error",
        });
        return;
      }

      if (this.zhituError) {
        uni.showToast({
          title: this.zhituError.status_desc,
          icon: "error",
        });
        return;
      }

      if (this.isFromIndex != 0) {
        this.zhituGetStartInfo();
      } else {
        this.gotoNext();
      }
      this.commitBuringPoint("clickBeginInterview");
    },

    gotoNext() {
      if (this.zhituBeginData && this.zhituBeginData.status == "finished") {
        uni.showToast({
          title: this.zhituBeginData.popUp,
          icon: "none",
        });
        return;
      }

      let data = {
        isFromIndex: this.isFromIndex,
        isTest: false,
        issure: this.issure,
        info: this.interviewInfo,
        zhituInfo: this.zhituInterviewInfo,
        zhituData: this.zhituBeginData,
      };
      console.log("🚀 ~ gotoNext ~ data:", data);
      uni.setStorage({
        key: "params-interviewReady",
        data: data,
        success: function () {
          uni.navigateTo({
            url: "./interviewBegin",
          });
        },
      });
    },
    commitBuringPoint(optCode) {
      let modelType = "";
      if (this.isFromIndex == 3) {
        modelType = "demonstrate";
      } else if (this.isFromIndex == 1) {
        modelType = "zph";
      } else {
        modelType = "zt";
      }
      let params = {
        optCode: optCode,
        platform: "1",
        personId: this.personId,
        moduleType: modelType,
        remark: this.channel,
      };
      refAddPoint(params).then((res) => {
        if (res.code == 200) {
          console.log("commitBuringPoint", optCode, res);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.background-pic {
  width: 100%;
  height: calc(100vw * (476 / 754));
}

.bottom-tip-box {
  margin-bottom: 10px;
  font-size: 14px;
  text-align: center;
}
.bottom-red-text {
  color: #f75a3e;
}
.fill-object {
  flex: 1;
}

.screen {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.centerImg1 {
  width: 100%;
  height: calc(100vw * (476 / 754));
}
.conter {
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  position: initial;
}

.interviewTitle {
  color: #000000;
  font-size: 20px;
  font-weight: bold;
}
.interviewTime {
  color: #333333;
  font-size: 14px;
  margin-top: 2px;
}
.interviewTip {
  color: #555555;
  font-size: 14px;
  text-align: center;
  margin: 16px 16px 10px;
}

.interviewBegin {
  width: 70%;
  margin-top: 10px;
  margin-bottom: 20px;
}
.imitate-interview {
  margin-top: 10px;
  margin-bottom: 20px;
  color: #f75a3e;
  width: 80%;
  height: 44px;
  line-height: 44px;
  font-size: 14px;
  text-align: center;
}
</style>
